package CC.Observer.Impl;

import CC.Observer.Publisher;
import CC.Observer.Subscriber;

import java.util.ArrayList;
import java.util.List;

public class WechatServer implements Publisher {

    //注意到这个List集合的泛型参数为Subscriber接口，
    //设计原则：面向接口编程而不是面向实现编程
    private List<Subscriber> list;
    //消息内容
    private String message;

    public WechatServer() {
        list = new ArrayList<Subscriber>();
    }

    @Override
    public void registerSubscriber(Subscriber s) {
        list.add(s);

    }

    @Override
    public void removeSubscriber(Subscriber s) {

        if (!list.isEmpty()){
            list.remove(s);
        }

    }

    @Override
    public void notifySubscriber() {
        for(int i = 0; i < list.size(); i++){
            Subscriber subscriber = list.get(i);
            subscriber.update(message);
        }

    }

    public void setInfomation(String s) {
        this.message = s;
        System.out.println("微信服务更新消息： " + s);
        //消息更新，通知所有观察者
        notifySubscriber();
    }
}
